





<!DOCTYPE html>
<html class="writer-html5" lang="zh-CN" >
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>构建一个图形卷积网络 &mdash; tvm 0.8.dev1982 文档</title>
  

  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/gallery.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/css/tlcpack_theme.css" type="text/css" />

  
  
    <link rel="shortcut icon" href="../../_static/tvm-logo-square.png"/>
  

  
  
  
  
    
      <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
        <script data-url_root="../../" id="documentation_options" src="../../_static/documentation_options.js"></script>
        <script src="../../_static/jquery.js"></script>
        <script src="../../_static/underscore.js"></script>
        <script src="../../_static/doctools.js"></script>
        <script src="../../_static/translations.js"></script>
        <script async="async" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
    
    <script type="text/javascript" src="../../_static/js/theme.js"></script>

    
    <script type="text/javascript" src="../../_static/js/tlcpack_theme.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="在Relay中使用外部库" href="using_external_lib.html" />
    <link rel="prev" title="Work With Relay" href="index.html" /> 
</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">
    
    
<header class="header">
    <div class="innercontainer">
      <div class="headerInner d-flex justify-content-between align-items-center">
          <div class="headerLogo">
               <a href="https://tvm.apache.org/"><img src=https://tvm.apache.org/assets/images/logo.svg alt="logo"></a>
          </div>

          <div id="headMenu" class="headerNav">
            <button type="button" id="closeHeadMenu" class="navCloseBtn"><img src="../../_static/img/close-icon.svg" alt="Close"></button>
             <ul class="nav">
                <li class="nav-item">
                   <a class="nav-link" href=https://tvm.apache.org/community>Community</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvm.apache.org/download>Download</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvm.apache.org/vta>VTA</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvm.apache.org/blog>Blog</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvm.apache.org/docs>Docs</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvmconf.org>Conference</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://github.com/apache/tvm/>Github</a>
                </li>
                <li class="nav-item">
                   <a class="nav-link" href=https://tvmchinese.github.io/declaration_zh_CN.html>About-Translators</a>
                </li>
             </ul>
               <div class="responsivetlcdropdown">
                 <button type="button" class="btn-link">
                   ASF
                 </button>
                 <ul>
                     <li>
                       <a href=https://apache.org/>Apache Homepage</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/licenses/>License</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/foundation/sponsorship.html>Sponsorship</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/security/>Security</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/foundation/thanks.html>Thanks</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/events/current-event>Events</a>
                     </li>
                     <li>
                       <a href=https://www.zhihu.com/column/c_1429578595417563136>Zhihu</a>
                     </li>
                 </ul>
               </div>
          </div>
            <div class="responsiveMenuIcon">
              <button type="button" id="menuBtn" class="btn-menu"><img src="../../_static/img/menu-icon.svg" alt="Menu Icon"></button>
            </div>

            <div class="tlcDropdown">
              <div class="dropdown">
                <button type="button" class="btn-link dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                  ASF
                </button>
                <div class="dropdown-menu dropdown-menu-right">
                  <ul>
                     <li>
                       <a href=https://apache.org/>Apache Homepage</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/licenses/>License</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/foundation/sponsorship.html>Sponsorship</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/security/>Security</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/foundation/thanks.html>Thanks</a>
                     </li>
                     <li>
                       <a href=https://www.apache.org/events/current-event>Events</a>
                     </li>
                     <li>
                       <a href=https://www.zhihu.com/column/c_1429578595417563136>Zhihu</a>
                     </li>
                  </ul>
                </div>
              </div>
          </div>
       </div>
    </div>
 </header>
 
    <nav data-toggle="wy-nav-shift" class="wy-nav-side fixed">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >
          

          
            <a href="../../index.html">
          

          
            
            <img src="../../_static/tvm-logo-small.png" class="logo" alt="Logo"/>
          
          </a>

          
            
            
                <div class="version">
                  0.8.dev1982
                </div>
            
          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        
        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <p class="caption" role="heading"><span class="caption-text">如何开始</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../install/index.html">安装 TVM</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../contribute/index.html">贡献者指南</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">用户引导</span></p>
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../../tutorial/index.html">User Tutorial</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../index.html">How To Guides</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="../compile_models/index.html">编译深度学习模型</a></li>
<li class="toctree-l2"><a class="reference internal" href="../deploy/index.html">TVM 部署模型和集成</a></li>
<li class="toctree-l2 current"><a class="reference internal" href="index.html">Work With Relay</a><ul class="current">
<li class="toctree-l3 current"><a class="current reference internal" href="#">构建一个图形卷积网络</a><ul>
<li class="toctree-l4"><a class="reference internal" href="#define-gcn-in-dgl-with-pytorch-backend">使用PyTorch后端在DGL中定义GCN</a></li>
<li class="toctree-l4"><a class="reference internal" href="#define-the-functions-to-load-dataset-and-evaluate-accuracy">定义加载数据集和评估准确性的代码</a></li>
<li class="toctree-l4"><a class="reference internal" href="#load-the-data-and-set-up-model-parameters">加载数据并设置模型参数</a></li>
<li class="toctree-l4"><a class="reference internal" href="#set-up-the-dgl-pytorch-model-and-get-the-golden-results">建立DGL-PyTorch模型并获得黄金结果</a></li>
<li class="toctree-l4"><a class="reference internal" href="#run-the-dgl-model-and-test-for-accuracy">运行DGL模型并测试其准确性</a></li>
<li class="toctree-l4"><a class="reference internal" href="#define-graph-convolution-layer-in-relay">定义Relay中的图形卷积</a></li>
<li class="toctree-l4"><a class="reference internal" href="#prepare-the-parameters-needed-in-the-graphconv-layers">准备GraphConv层中所需的参数</a></li>
<li class="toctree-l4"><a class="reference internal" href="#put-layers-together">将层放在一起</a></li>
<li class="toctree-l4"><a class="reference internal" href="#compile-and-run-with-tvm">使用VTM编译和运行</a></li>
<li class="toctree-l4"><a class="reference internal" href="#run-the-tvm-model-test-for-accuracy-and-verify-with-dgl">运行TVM模型，测试精度并使用DGL进行验证</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="using_external_lib.html">在Relay中使用外部库</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../work_with_schedules/index.html">Work With Tensor Expression and Schedules</a></li>
<li class="toctree-l2"><a class="reference internal" href="../optimize_operators/index.html">优化张量算子</a></li>
<li class="toctree-l2"><a class="reference internal" href="../tune_with_autotvm/index.html">Auto-Tune with Templates and AutoTVM</a></li>
<li class="toctree-l2"><a class="reference internal" href="../tune_with_autoscheduler/index.html">Use AutoScheduler for Template-Free Scheduling</a></li>
<li class="toctree-l2"><a class="reference internal" href="../work_with_microtvm/index.html">Work With microTVM</a></li>
<li class="toctree-l2"><a class="reference internal" href="../extend_tvm/index.html">Extend TVM</a></li>
<li class="toctree-l2"><a class="reference internal" href="../profile/index.html">Profile Models</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../errors.html">Handle TVM Errors</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../faq.html">常见提问</a></li>
</ul>
</li>
</ul>
<p class="caption" role="heading"><span class="caption-text">开发者引导</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../dev/tutorial/index.html">Developer Tutorial</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../dev/how_to/how_to.html">开发者指南</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">架构指南</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../arch/index.html">Design and Architecture</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">主题引导</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../topic/microtvm/index.html">microTVM：裸机使用TVM</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../topic/vta/index.html">VTA: Versatile Tensor Accelerator</a></li>
</ul>
<p class="caption" role="heading"><span class="caption-text">参考指南</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../reference/langref/index.html">语言参考</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../reference/api/python/index.html">Python API</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../reference/api/links.html">Other APIs</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../reference/publications.html">Publications</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../genindex.html">索引</a></li>
</ul>

            
          
        </div>
        
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
      
      <nav class="wy-nav-top" aria-label="top navigation" data-toggle="wy-nav-top">
        
            <div class="togglemenu">

            </div>
            <div class="nav-content">
              <!-- tvm -->
              Table of content
            </div>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        

          




















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../../index.html">Docs</a> <span class="br-arrow">></span></li>
        
          <li><a href="../index.html">How To Guides</a> <span class="br-arrow">></span></li>
        
          <li><a href="index.html">Work With Relay</a> <span class="br-arrow">></span></li>
        
      <li>构建一个图形卷积网络</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
            
            <a href="../../_sources/how_to/work_with_relay/build_gcn.rst.txt" rel="nofollow"> <img src="../../_static//img/source.svg" alt="viewsource"/></a>
          
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <div class="sphx-glr-download-link-note admonition note">
<p class="admonition-title">注解</p>
<p>Click <a class="reference internal" href="#sphx-glr-download-how-to-work-with-relay-build-gcn-py"><span class="std std-ref">here</span></a> to download the full example code</p>
</div>
<div class="sphx-glr-example-title section" id="building-a-graph-convolutional-network">
<span id="sphx-glr-how-to-work-with-relay-build-gcn-py"></span><h1>构建一个图形卷积网络<a class="headerlink" href="#building-a-graph-convolutional-network" title="永久链接至标题">¶</a></h1>
<p><strong>作者</strong>: <a class="reference external" href="https://yulunyao.io/">Yulun Yao</a>,             <a class="reference external" href="https://homes.cs.washington.edu/~cyulin/">Chien-Yu Lin</a></p>
<p>本文是一篇介绍如何使用Relay构建图形卷积网络（GCN）的介绍性教程。在本教程中，我们将在Cora数据集上运行GCN进行演示。Cora数据集是图形神经网络（GNN）和支持GNN训练和推理的框架的通用基准。我们直接从DGL库中加载数据集，对DGL进行同类之间的比较。</p>
<p>请参阅DGL指南，了解DGL的安装https://docs.dgl.ai/install/index.html.</p>
<p>请参阅PyTorch指南，了解PyTorch的安装https://pytorch.org/get-started/locally/.</p>
<div class="section" id="define-gcn-in-dgl-with-pytorch-backend">
<h2>使用PyTorch后端在DGL中定义GCN<a class="headerlink" href="#define-gcn-in-dgl-with-pytorch-backend" title="永久链接至标题">¶</a></h2>
<p>DGL示例：<a class="reference external" href="https://github.com/dmlc/dgl/tree/master/examples/pytorch/gcn">https://github.com/dmlc/dgl/tree/master/examples/pytorch/gcn</a> 这一部分重复使用了上述示例中的代码。</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">torch</span>
<span class="kn">import</span> <span class="nn">torch.nn</span> <span class="k">as</span> <span class="nn">nn</span>
<span class="kn">import</span> <span class="nn">torch.nn.functional</span> <span class="k">as</span> <span class="nn">F</span>
<span class="kn">import</span> <span class="nn">dgl</span>
<span class="kn">import</span> <span class="nn">networkx</span> <span class="k">as</span> <span class="nn">nx</span>
<span class="kn">from</span> <span class="nn">dgl.nn.pytorch</span> <span class="k">import</span> <span class="n">GraphConv</span>


<span class="k">class</span> <span class="nc">GCN</span><span class="p">(</span><span class="n">nn</span><span class="o">.</span><span class="n">Module</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">g</span><span class="p">,</span> <span class="n">n_infeat</span><span class="p">,</span> <span class="n">n_hidden</span><span class="p">,</span> <span class="n">n_classes</span><span class="p">,</span> <span class="n">n_layers</span><span class="p">,</span> <span class="n">activation</span><span class="p">):</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">GCN</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">g</span> <span class="o">=</span> <span class="n">g</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">layers</span> <span class="o">=</span> <span class="n">nn</span><span class="o">.</span><span class="n">ModuleList</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">GraphConv</span><span class="p">(</span><span class="n">n_infeat</span><span class="p">,</span> <span class="n">n_hidden</span><span class="p">,</span> <span class="n">activation</span><span class="o">=</span><span class="n">activation</span><span class="p">))</span>
        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_layers</span> <span class="o">-</span> <span class="mi">1</span><span class="p">):</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">GraphConv</span><span class="p">(</span><span class="n">n_hidden</span><span class="p">,</span> <span class="n">n_hidden</span><span class="p">,</span> <span class="n">activation</span><span class="o">=</span><span class="n">activation</span><span class="p">))</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">GraphConv</span><span class="p">(</span><span class="n">n_hidden</span><span class="p">,</span> <span class="n">n_classes</span><span class="p">))</span>

    <span class="k">def</span> <span class="nf">forward</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">features</span><span class="p">):</span>
        <span class="n">h</span> <span class="o">=</span> <span class="n">features</span>
        <span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">layer</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">layers</span><span class="p">):</span>
            <span class="c1"># handle api changes for differnt DGL version</span>
            <span class="k">if</span> <span class="n">dgl</span><span class="o">.</span><span class="n">__version__</span> <span class="o">&gt;</span> <span class="s2">&quot;0.3&quot;</span><span class="p">:</span>
                <span class="n">h</span> <span class="o">=</span> <span class="n">layer</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">g</span><span class="p">,</span> <span class="n">h</span><span class="p">)</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">h</span> <span class="o">=</span> <span class="n">layer</span><span class="p">(</span><span class="n">h</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">g</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">h</span>
</pre></div>
</div>
<p class="sphx-glr-script-out">输出:</p>
<div class="sphx-glr-script-out highlight-none notranslate"><div class="highlight"><pre><span></span>Using backend: pytorch
</pre></div>
</div>
</div>
<div class="section" id="define-the-functions-to-load-dataset-and-evaluate-accuracy">
<h2>定义加载数据集和评估准确性的代码<a class="headerlink" href="#define-the-functions-to-load-dataset-and-evaluate-accuracy" title="永久链接至标题">¶</a></h2>
<p>您可以用自己的数据集替换此部分，这里我们从DGL加载数据</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">dgl.data</span> <span class="k">import</span> <span class="n">load_data</span>
<span class="kn">from</span> <span class="nn">collections</span> <span class="k">import</span> <span class="n">namedtuple</span>


<span class="k">def</span> <span class="nf">load_dataset</span><span class="p">(</span><span class="n">dataset</span><span class="o">=</span><span class="s2">&quot;cora&quot;</span><span class="p">):</span>
    <span class="n">args</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s2">&quot;args&quot;</span><span class="p">,</span> <span class="p">[</span><span class="s2">&quot;dataset&quot;</span><span class="p">])</span>
    <span class="n">data</span> <span class="o">=</span> <span class="n">load_data</span><span class="p">(</span><span class="n">args</span><span class="p">(</span><span class="n">dataset</span><span class="p">))</span>

    <span class="c1"># Remove self-loops to avoid duplicate passing of a node&#39;s feature to itself</span>
    <span class="n">g</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">graph</span>
    <span class="n">g</span><span class="o">.</span><span class="n">remove_edges_from</span><span class="p">(</span><span class="n">nx</span><span class="o">.</span><span class="n">selfloop_edges</span><span class="p">(</span><span class="n">g</span><span class="p">))</span>
    <span class="n">g</span><span class="o">.</span><span class="n">add_edges_from</span><span class="p">(</span><span class="nb">zip</span><span class="p">(</span><span class="n">g</span><span class="o">.</span><span class="n">nodes</span><span class="p">,</span> <span class="n">g</span><span class="o">.</span><span class="n">nodes</span><span class="p">))</span>

    <span class="k">return</span> <span class="n">g</span><span class="p">,</span> <span class="n">data</span>


<span class="k">def</span> <span class="nf">evaluate</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">logits</span><span class="p">):</span>
    <span class="n">test_mask</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">test_mask</span>  <span class="c1"># the test set which isn&#39;t included in the training phase</span>

    <span class="n">pred</span> <span class="o">=</span> <span class="n">logits</span><span class="o">.</span><span class="n">argmax</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
    <span class="n">acc</span> <span class="o">=</span> <span class="p">((</span><span class="n">pred</span> <span class="o">==</span> <span class="n">data</span><span class="o">.</span><span class="n">labels</span><span class="p">)</span> <span class="o">*</span> <span class="n">test_mask</span><span class="p">)</span><span class="o">.</span><span class="n">sum</span><span class="p">()</span> <span class="o">/</span> <span class="n">test_mask</span><span class="o">.</span><span class="n">sum</span><span class="p">()</span>

    <span class="k">return</span> <span class="n">acc</span>
</pre></div>
</div>
</div>
<div class="section" id="load-the-data-and-set-up-model-parameters">
<h2>加载数据并设置模型参数<a class="headerlink" href="#load-the-data-and-set-up-model-parameters" title="永久链接至标题">¶</a></h2>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">Parameters</span>
<span class="sd">----------</span>
<span class="sd">dataset: str</span>
<span class="sd">    Name of dataset. You can choose from [&#39;cora&#39;, &#39;citeseer&#39;, &#39;pubmed&#39;].</span>

<span class="sd">num_layer: int</span>
<span class="sd">    number of hidden layers</span>

<span class="sd">num_hidden: int</span>
<span class="sd">    number of the hidden units in the hidden layer</span>

<span class="sd">infeat_dim: int</span>
<span class="sd">    dimension of the input features</span>

<span class="sd">num_classes: int</span>
<span class="sd">    dimension of model output (Number of classes)</span>
<span class="sd">&quot;&quot;&quot;</span>
<span class="n">dataset</span> <span class="o">=</span> <span class="s2">&quot;cora&quot;</span>

<span class="n">g</span><span class="p">,</span> <span class="n">data</span> <span class="o">=</span> <span class="n">load_dataset</span><span class="p">(</span><span class="n">dataset</span><span class="p">)</span>

<span class="n">num_layers</span> <span class="o">=</span> <span class="mi">1</span>
<span class="n">num_hidden</span> <span class="o">=</span> <span class="mi">16</span>
<span class="n">infeat_dim</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">features</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="n">num_classes</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">num_labels</span>
</pre></div>
</div>
<p class="sphx-glr-script-out">输出:</p>
<div class="sphx-glr-script-out highlight-none notranslate"><div class="highlight"><pre><span></span>  NumNodes: 2708
  NumEdges: 10556
  NumFeats: 1433
  NumClasses: 7
  NumTrainingSamples: 140
  NumValidationSamples: 500
  NumTestSamples: 1000
Done loading data from cached files.
/usr/local/lib/python3.6/dist-packages/dgl/data/utils.py:285: UserWarning: Property dataset.graph will be deprecated, please use dataset[0] instead.
  warnings.warn(&#39;Property {} will be deprecated, please use {} instead.&#39;.format(old, new))
/usr/local/lib/python3.6/dist-packages/dgl/data/utils.py:285: UserWarning: Property dataset.feat will be deprecated, please use g.ndata[&#39;feat&#39;] instead.
  warnings.warn(&#39;Property {} will be deprecated, please use {} instead.&#39;.format(old, new))
/usr/local/lib/python3.6/dist-packages/dgl/data/utils.py:285: UserWarning: Property dataset.num_labels will be deprecated, please use dataset.num_classes instead.
  warnings.warn(&#39;Property {} will be deprecated, please use {} instead.&#39;.format(old, new))
</pre></div>
</div>
</div>
<div class="section" id="set-up-the-dgl-pytorch-model-and-get-the-golden-results">
<h2>建立DGL-PyTorch模型并获得黄金结果<a class="headerlink" href="#set-up-the-dgl-pytorch-model-and-get-the-golden-results" title="永久链接至标题">¶</a></h2>
<p><a class="reference external" href="https://github.com/dmlc/dgl/blob/master/examples/pytorch/gcn/train.py">https://github.com/dmlc/dgl/blob/master/examples/pytorch/gcn/train.py</a> 训练权重</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">tvm.contrib.download</span> <span class="k">import</span> <span class="n">download_testdata</span>
<span class="kn">from</span> <span class="nn">dgl</span> <span class="k">import</span> <span class="n">DGLGraph</span>

<span class="n">features</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">FloatTensor</span><span class="p">(</span><span class="n">data</span><span class="o">.</span><span class="n">features</span><span class="p">)</span>
<span class="n">dgl_g</span> <span class="o">=</span> <span class="n">DGLGraph</span><span class="p">(</span><span class="n">g</span><span class="p">)</span>

<span class="n">torch_model</span> <span class="o">=</span> <span class="n">GCN</span><span class="p">(</span><span class="n">dgl_g</span><span class="p">,</span> <span class="n">infeat_dim</span><span class="p">,</span> <span class="n">num_hidden</span><span class="p">,</span> <span class="n">num_classes</span><span class="p">,</span> <span class="n">num_layers</span><span class="p">,</span> <span class="n">F</span><span class="o">.</span><span class="n">relu</span><span class="p">)</span>

<span class="c1"># Download the pretrained weights</span>
<span class="n">model_url</span> <span class="o">=</span> <span class="s2">&quot;https://homes.cs.washington.edu/~cyulin/media/gnn_model/gcn_</span><span class="si">%s</span><span class="s2">.torch&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">dataset</span><span class="p">)</span>
<span class="n">model_path</span> <span class="o">=</span> <span class="n">download_testdata</span><span class="p">(</span><span class="n">model_url</span><span class="p">,</span> <span class="s2">&quot;gcn_</span><span class="si">%s</span><span class="s2">.pickle&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">dataset</span><span class="p">),</span> <span class="n">module</span><span class="o">=</span><span class="s2">&quot;gcn_model&quot;</span><span class="p">)</span>

<span class="c1"># Load the weights into the model</span>
<span class="n">torch_model</span><span class="o">.</span><span class="n">load_state_dict</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">model_path</span><span class="p">))</span>
</pre></div>
</div>
<p class="sphx-glr-script-out">输出:</p>
<div class="sphx-glr-script-out highlight-none notranslate"><div class="highlight"><pre><span></span>/usr/local/lib/python3.6/dist-packages/dgl/base.py:45: DGLWarning: Recommend creating graphs by `dgl.graph(data)` instead of `dgl.DGLGraph(data)`.
  return warnings.warn(message, category=category, stacklevel=1)
</pre></div>
</div>
</div>
<div class="section" id="run-the-dgl-model-and-test-for-accuracy">
<h2>运行DGL模型并测试其准确性<a class="headerlink" href="#run-the-dgl-model-and-test-for-accuracy" title="永久链接至标题">¶</a></h2>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">torch_model</span><span class="o">.</span><span class="n">eval</span><span class="p">()</span>
<span class="k">with</span> <span class="n">torch</span><span class="o">.</span><span class="n">no_grad</span><span class="p">():</span>
    <span class="n">logits_torch</span> <span class="o">=</span> <span class="n">torch_model</span><span class="p">(</span><span class="n">features</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Print the first five outputs from DGL-PyTorch execution</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">logits_torch</span><span class="p">[:</span><span class="mi">5</span><span class="p">])</span>

<span class="n">acc</span> <span class="o">=</span> <span class="n">evaluate</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">logits_torch</span><span class="o">.</span><span class="n">numpy</span><span class="p">())</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Test accuracy of DGL results: </span><span class="si">{:.2%}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">acc</span><span class="p">))</span>
</pre></div>
</div>
<p class="sphx-glr-script-out">输出:</p>
<div class="sphx-glr-script-out highlight-none notranslate"><div class="highlight"><pre><span></span>Print the first five outputs from DGL-PyTorch execution
 tensor([[-2.2395, -0.9681,  3.4042, -0.1481, -0.0272, -1.2441, -1.8549],
        [-1.6017, -1.3846,  0.7642,  2.5430, -1.7420, -1.3704,  0.4249],
        [-2.0039, -1.2357,  2.4931,  1.0323, -1.3252, -1.3401, -0.5114],
        [ 0.1647, -2.0421, -0.2668,  0.1527, -0.6965,  1.1109,  1.1034],
        [-0.8606, -0.6954,  0.1959,  0.6853,  0.0284, -0.6652,  0.2225]])
/usr/local/lib/python3.6/dist-packages/dgl/data/utils.py:285: UserWarning: Property dataset.test_mask will be deprecated, please use g.ndata[&#39;test_mask&#39;] instead.
  warnings.warn(&#39;Property {} will be deprecated, please use {} instead.&#39;.format(old, new))
/usr/local/lib/python3.6/dist-packages/dgl/data/utils.py:285: UserWarning: Property dataset.label will be deprecated, please use g.ndata[&#39;label&#39;] instead.
  warnings.warn(&#39;Property {} will be deprecated, please use {} instead.&#39;.format(old, new))
Test accuracy of DGL results: 5.30%
</pre></div>
</div>
</div>
<div class="section" id="define-graph-convolution-layer-in-relay">
<h2>定义Relay中的图形卷积<a class="headerlink" href="#define-graph-convolution-layer-in-relay" title="永久链接至标题">¶</a></h2>
<p>要在TVM上运行GCN，我们首先需要使图形卷积生效。你可以参考https://github.com/dmlc/dgl/blob/master/python/dgl/nn/mxnet/conv/graphconv.py 此网址使用MXNet后端在DGL中实现图形卷积。</p>
<p>该层由以下操作定义，请注意我们应用两个转置将邻接矩阵保留在稀疏_稠密算子的右侧，该方法是临时的，当我们有稀疏矩阵转置并支持左侧稀疏算子时，该方法将在未来几周内更新</p>
<blockquote>
<div><div class="math notranslate nohighlight">
\[\mbox{GraphConv}(A, H, W)   = A * H * W
                            = ((H * W)^t * A^t)^t
                            = ((W^t * H^t) * A^t)^t\]</div>
</div></blockquote>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">tvm</span> <span class="k">import</span> <span class="n">relay</span>
<span class="kn">from</span> <span class="nn">tvm.contrib</span> <span class="k">import</span> <span class="n">graph_executor</span>
<span class="kn">import</span> <span class="nn">tvm</span>
<span class="kn">from</span> <span class="nn">tvm</span> <span class="k">import</span> <span class="n">te</span>


<span class="k">def</span> <span class="nf">GraphConv</span><span class="p">(</span><span class="n">layer_name</span><span class="p">,</span> <span class="n">input_dim</span><span class="p">,</span> <span class="n">output_dim</span><span class="p">,</span> <span class="n">adj</span><span class="p">,</span> <span class="nb">input</span><span class="p">,</span> <span class="n">norm</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">bias</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">activation</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Parameters</span>
<span class="sd">    ----------</span>
<span class="sd">    layer_name: str</span>
<span class="sd">    Name of layer</span>

<span class="sd">    input_dim: int</span>
<span class="sd">    Input dimension per node feature</span>

<span class="sd">    output_dim: int,</span>
<span class="sd">    Output dimension per node feature</span>

<span class="sd">    adj: namedtuple,</span>
<span class="sd">    Graph representation (Adjacency Matrix) in Sparse Format (`data`, `indices`, `indptr`),</span>
<span class="sd">    where `data` has shape [num_nonzeros], indices` has shape [num_nonzeros], `indptr` has shape [num_nodes + 1]</span>

<span class="sd">    input: relay.Expr,</span>
<span class="sd">    Input feature to current layer with shape [num_nodes, input_dim]</span>

<span class="sd">    norm: relay.Expr,</span>
<span class="sd">    Norm passed to this layer to normalize features before and after Convolution.</span>

<span class="sd">    bias: bool</span>
<span class="sd">    Set bias to True to add bias when doing GCN layer</span>

<span class="sd">    activation: &lt;function relay.op.nn&gt;,</span>
<span class="sd">    Activation function applies to the output. e.g. relay.nn.{relu, sigmoid, log_softmax, softmax, leaky_relu}</span>

<span class="sd">    Returns</span>
<span class="sd">    ----------</span>
<span class="sd">    output: tvm.relay.Expr</span>
<span class="sd">    The Output Tensor for this layer [num_nodes, output_dim]</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="n">norm</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
        <span class="nb">input</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">multiply</span><span class="p">(</span><span class="nb">input</span><span class="p">,</span> <span class="n">norm</span><span class="p">)</span>

    <span class="n">weight</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">var</span><span class="p">(</span><span class="n">layer_name</span> <span class="o">+</span> <span class="s2">&quot;.weight&quot;</span><span class="p">,</span> <span class="n">shape</span><span class="o">=</span><span class="p">(</span><span class="n">input_dim</span><span class="p">,</span> <span class="n">output_dim</span><span class="p">))</span>
    <span class="n">weight_t</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">transpose</span><span class="p">(</span><span class="n">weight</span><span class="p">)</span>
    <span class="n">dense</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">dense</span><span class="p">(</span><span class="n">weight_t</span><span class="p">,</span> <span class="nb">input</span><span class="p">)</span>
    <span class="n">output</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">sparse_dense</span><span class="p">(</span><span class="n">dense</span><span class="p">,</span> <span class="n">adj</span><span class="p">)</span>
    <span class="n">output_t</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">transpose</span><span class="p">(</span><span class="n">output</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">norm</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">output_t</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">multiply</span><span class="p">(</span><span class="n">output_t</span><span class="p">,</span> <span class="n">norm</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">bias</span> <span class="ow">is</span> <span class="kc">True</span><span class="p">:</span>
        <span class="n">_bias</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">var</span><span class="p">(</span><span class="n">layer_name</span> <span class="o">+</span> <span class="s2">&quot;.bias&quot;</span><span class="p">,</span> <span class="n">shape</span><span class="o">=</span><span class="p">(</span><span class="n">output_dim</span><span class="p">,</span> <span class="mi">1</span><span class="p">))</span>
        <span class="n">output_t</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">bias_add</span><span class="p">(</span><span class="n">output_t</span><span class="p">,</span> <span class="n">_bias</span><span class="p">,</span> <span class="n">axis</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">activation</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">output_t</span> <span class="o">=</span> <span class="n">activation</span><span class="p">(</span><span class="n">output_t</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">output_t</span>
</pre></div>
</div>
</div>
<div class="section" id="prepare-the-parameters-needed-in-the-graphconv-layers">
<h2>准备GraphConv层中所需的参数<a class="headerlink" href="#prepare-the-parameters-needed-in-the-graphconv-layers" title="永久链接至标题">¶</a></h2>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">networkx</span> <span class="k">as</span> <span class="nn">nx</span>


<span class="k">def</span> <span class="nf">prepare_params</span><span class="p">(</span><span class="n">g</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
    <span class="n">params</span> <span class="o">=</span> <span class="p">{}</span>
    <span class="n">params</span><span class="p">[</span><span class="s2">&quot;infeats&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">features</span><span class="o">.</span><span class="n">numpy</span><span class="p">()</span><span class="o">.</span><span class="n">astype</span><span class="p">(</span>
        <span class="s2">&quot;float32&quot;</span>
    <span class="p">)</span>  <span class="c1"># Only support float32 as feature for now</span>

    <span class="c1"># Generate adjacency matrix</span>
    <span class="n">adjacency</span> <span class="o">=</span> <span class="n">nx</span><span class="o">.</span><span class="n">to_scipy_sparse_matrix</span><span class="p">(</span><span class="n">g</span><span class="p">)</span>
    <span class="n">params</span><span class="p">[</span><span class="s2">&quot;g_data&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="n">adjacency</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">astype</span><span class="p">(</span><span class="s2">&quot;float32&quot;</span><span class="p">)</span>
    <span class="n">params</span><span class="p">[</span><span class="s2">&quot;indices&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="n">adjacency</span><span class="o">.</span><span class="n">indices</span><span class="o">.</span><span class="n">astype</span><span class="p">(</span><span class="s2">&quot;int32&quot;</span><span class="p">)</span>
    <span class="n">params</span><span class="p">[</span><span class="s2">&quot;indptr&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="n">adjacency</span><span class="o">.</span><span class="n">indptr</span><span class="o">.</span><span class="n">astype</span><span class="p">(</span><span class="s2">&quot;int32&quot;</span><span class="p">)</span>

    <span class="c1"># Normalization w.r.t. node degrees</span>
    <span class="n">degs</span> <span class="o">=</span> <span class="p">[</span><span class="n">g</span><span class="o">.</span><span class="n">in_degree</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">g</span><span class="o">.</span><span class="n">number_of_nodes</span><span class="p">())]</span>
    <span class="n">params</span><span class="p">[</span><span class="s2">&quot;norm&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">power</span><span class="p">(</span><span class="n">degs</span><span class="p">,</span> <span class="o">-</span><span class="mf">0.5</span><span class="p">)</span><span class="o">.</span><span class="n">astype</span><span class="p">(</span><span class="s2">&quot;float32&quot;</span><span class="p">)</span>
    <span class="n">params</span><span class="p">[</span><span class="s2">&quot;norm&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="n">params</span><span class="p">[</span><span class="s2">&quot;norm&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">reshape</span><span class="p">((</span><span class="n">params</span><span class="p">[</span><span class="s2">&quot;norm&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="mi">1</span><span class="p">))</span>

    <span class="k">return</span> <span class="n">params</span>


<span class="n">params</span> <span class="o">=</span> <span class="n">prepare_params</span><span class="p">(</span><span class="n">g</span><span class="p">,</span> <span class="n">data</span><span class="p">)</span>

<span class="c1"># Check shape of features and the validity of adjacency matrix</span>
<span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="s2">&quot;infeats&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span> <span class="o">==</span> <span class="mi">2</span>
<span class="k">assert</span> <span class="p">(</span>
    <span class="n">params</span><span class="p">[</span><span class="s2">&quot;g_data&quot;</span><span class="p">]</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">params</span><span class="p">[</span><span class="s2">&quot;indices&quot;</span><span class="p">]</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">params</span><span class="p">[</span><span class="s2">&quot;indptr&quot;</span><span class="p">]</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span>
<span class="p">)</span>
<span class="k">assert</span> <span class="n">params</span><span class="p">[</span><span class="s2">&quot;infeats&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">==</span> <span class="n">params</span><span class="p">[</span><span class="s2">&quot;indptr&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">-</span> <span class="mi">1</span>
</pre></div>
</div>
</div>
<div class="section" id="put-layers-together">
<h2>将层放在一起<a class="headerlink" href="#put-layers-together" title="永久链接至标题">¶</a></h2>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Define input features, norms, adjacency matrix in Relay</span>
<span class="n">infeats</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">var</span><span class="p">(</span><span class="s2">&quot;infeats&quot;</span><span class="p">,</span> <span class="n">shape</span><span class="o">=</span><span class="n">data</span><span class="o">.</span><span class="n">features</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span>
<span class="n">norm</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">Constant</span><span class="p">(</span><span class="n">tvm</span><span class="o">.</span><span class="n">nd</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="s2">&quot;norm&quot;</span><span class="p">]))</span>
<span class="n">g_data</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">Constant</span><span class="p">(</span><span class="n">tvm</span><span class="o">.</span><span class="n">nd</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="s2">&quot;g_data&quot;</span><span class="p">]))</span>
<span class="n">indices</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">Constant</span><span class="p">(</span><span class="n">tvm</span><span class="o">.</span><span class="n">nd</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="s2">&quot;indices&quot;</span><span class="p">]))</span>
<span class="n">indptr</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">Constant</span><span class="p">(</span><span class="n">tvm</span><span class="o">.</span><span class="n">nd</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="s2">&quot;indptr&quot;</span><span class="p">]))</span>

<span class="n">Adjacency</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s2">&quot;Adjacency&quot;</span><span class="p">,</span> <span class="p">[</span><span class="s2">&quot;data&quot;</span><span class="p">,</span> <span class="s2">&quot;indices&quot;</span><span class="p">,</span> <span class="s2">&quot;indptr&quot;</span><span class="p">])</span>
<span class="n">adj</span> <span class="o">=</span> <span class="n">Adjacency</span><span class="p">(</span><span class="n">g_data</span><span class="p">,</span> <span class="n">indices</span><span class="p">,</span> <span class="n">indptr</span><span class="p">)</span>

<span class="c1"># Construct the 2-layer GCN</span>
<span class="n">layers</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">layers</span><span class="o">.</span><span class="n">append</span><span class="p">(</span>
    <span class="n">GraphConv</span><span class="p">(</span>
        <span class="n">layer_name</span><span class="o">=</span><span class="s2">&quot;layers.0&quot;</span><span class="p">,</span>
        <span class="n">input_dim</span><span class="o">=</span><span class="n">infeat_dim</span><span class="p">,</span>
        <span class="n">output_dim</span><span class="o">=</span><span class="n">num_hidden</span><span class="p">,</span>
        <span class="n">adj</span><span class="o">=</span><span class="n">adj</span><span class="p">,</span>
        <span class="nb">input</span><span class="o">=</span><span class="n">infeats</span><span class="p">,</span>
        <span class="n">norm</span><span class="o">=</span><span class="n">norm</span><span class="p">,</span>
        <span class="n">activation</span><span class="o">=</span><span class="n">relay</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">relu</span><span class="p">,</span>
    <span class="p">)</span>
<span class="p">)</span>
<span class="n">layers</span><span class="o">.</span><span class="n">append</span><span class="p">(</span>
    <span class="n">GraphConv</span><span class="p">(</span>
        <span class="n">layer_name</span><span class="o">=</span><span class="s2">&quot;layers.1&quot;</span><span class="p">,</span>
        <span class="n">input_dim</span><span class="o">=</span><span class="n">num_hidden</span><span class="p">,</span>
        <span class="n">output_dim</span><span class="o">=</span><span class="n">num_classes</span><span class="p">,</span>
        <span class="n">adj</span><span class="o">=</span><span class="n">adj</span><span class="p">,</span>
        <span class="nb">input</span><span class="o">=</span><span class="n">layers</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">],</span>
        <span class="n">norm</span><span class="o">=</span><span class="n">norm</span><span class="p">,</span>
        <span class="n">activation</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
    <span class="p">)</span>
<span class="p">)</span>

<span class="c1"># Analyze free variables and generate Relay function</span>
<span class="n">output</span> <span class="o">=</span> <span class="n">layers</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
</pre></div>
</div>
</div>
<div class="section" id="compile-and-run-with-tvm">
<h2>使用VTM编译和运行<a class="headerlink" href="#compile-and-run-with-tvm" title="永久链接至标题">¶</a></h2>
<p>将 Pytorch 模型的权重导出成 Python Dict</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">model_params</span> <span class="o">=</span> <span class="p">{}</span>
<span class="k">for</span> <span class="n">param_tensor</span> <span class="ow">in</span> <span class="n">torch_model</span><span class="o">.</span><span class="n">state_dict</span><span class="p">():</span>
    <span class="n">model_params</span><span class="p">[</span><span class="n">param_tensor</span><span class="p">]</span> <span class="o">=</span> <span class="n">torch_model</span><span class="o">.</span><span class="n">state_dict</span><span class="p">()[</span><span class="n">param_tensor</span><span class="p">]</span><span class="o">.</span><span class="n">numpy</span><span class="p">()</span>

<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">num_layers</span> <span class="o">+</span> <span class="mi">1</span><span class="p">):</span>
    <span class="n">params</span><span class="p">[</span><span class="s2">&quot;layers.</span><span class="si">%d</span><span class="s2">.weight&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">i</span><span class="p">)]</span> <span class="o">=</span> <span class="n">model_params</span><span class="p">[</span><span class="s2">&quot;layers.</span><span class="si">%d</span><span class="s2">.weight&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">i</span><span class="p">)]</span>
    <span class="n">params</span><span class="p">[</span><span class="s2">&quot;layers.</span><span class="si">%d</span><span class="s2">.bias&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">i</span><span class="p">)]</span> <span class="o">=</span> <span class="n">model_params</span><span class="p">[</span><span class="s2">&quot;layers.</span><span class="si">%d</span><span class="s2">.bias&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">i</span><span class="p">)]</span>

<span class="c1"># Set the TVM build target</span>
<span class="n">target</span> <span class="o">=</span> <span class="s2">&quot;llvm&quot;</span>  <span class="c1"># Currently only support `llvm` as target</span>

<span class="n">func</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">Function</span><span class="p">(</span><span class="n">relay</span><span class="o">.</span><span class="n">analysis</span><span class="o">.</span><span class="n">free_vars</span><span class="p">(</span><span class="n">output</span><span class="p">),</span> <span class="n">output</span><span class="p">)</span>
<span class="n">func</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">build_module</span><span class="o">.</span><span class="n">bind_params_by_name</span><span class="p">(</span><span class="n">func</span><span class="p">,</span> <span class="n">params</span><span class="p">)</span>
<span class="n">mod</span> <span class="o">=</span> <span class="n">tvm</span><span class="o">.</span><span class="n">IRModule</span><span class="p">()</span>
<span class="n">mod</span><span class="p">[</span><span class="s2">&quot;main&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="n">func</span>
<span class="c1"># Build with Relay</span>
<span class="k">with</span> <span class="n">tvm</span><span class="o">.</span><span class="n">transform</span><span class="o">.</span><span class="n">PassContext</span><span class="p">(</span><span class="n">opt_level</span><span class="o">=</span><span class="mi">0</span><span class="p">):</span>  <span class="c1"># Currently only support opt_level=0</span>
    <span class="n">lib</span> <span class="o">=</span> <span class="n">relay</span><span class="o">.</span><span class="n">build</span><span class="p">(</span><span class="n">mod</span><span class="p">,</span> <span class="n">target</span><span class="p">,</span> <span class="n">params</span><span class="o">=</span><span class="n">params</span><span class="p">)</span>

<span class="c1"># Generate graph executor</span>
<span class="n">dev</span> <span class="o">=</span> <span class="n">tvm</span><span class="o">.</span><span class="n">device</span><span class="p">(</span><span class="n">target</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="n">m</span> <span class="o">=</span> <span class="n">graph_executor</span><span class="o">.</span><span class="n">GraphModule</span><span class="p">(</span><span class="n">lib</span><span class="p">[</span><span class="s2">&quot;default&quot;</span><span class="p">](</span><span class="n">dev</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="section" id="run-the-tvm-model-test-for-accuracy-and-verify-with-dgl">
<h2>运行TVM模型，测试精度并使用DGL进行验证<a class="headerlink" href="#run-the-tvm-model-test-for-accuracy-and-verify-with-dgl" title="永久链接至标题">¶</a></h2>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">m</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>
<span class="n">logits_tvm</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">get_output</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span><span class="o">.</span><span class="n">numpy</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Print the first five outputs from TVM execution</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">logits_tvm</span><span class="p">[:</span><span class="mi">5</span><span class="p">])</span>

<span class="n">labels</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">labels</span>
<span class="n">test_mask</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">test_mask</span>

<span class="n">acc</span> <span class="o">=</span> <span class="n">evaluate</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">logits_tvm</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Test accuracy of TVM results: </span><span class="si">{:.2%}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">acc</span><span class="p">))</span>

<span class="kn">import</span> <span class="nn">tvm.testing</span>

<span class="c1"># Verify the results with the DGL model</span>
<span class="n">tvm</span><span class="o">.</span><span class="n">testing</span><span class="o">.</span><span class="n">assert_allclose</span><span class="p">(</span><span class="n">logits_torch</span><span class="p">,</span> <span class="n">logits_tvm</span><span class="p">,</span> <span class="n">atol</span><span class="o">=</span><span class="mf">1e-3</span><span class="p">)</span>
</pre></div>
</div>
<p class="sphx-glr-script-out">输出:</p>
<div class="sphx-glr-script-out highlight-none notranslate"><div class="highlight"><pre><span></span>Print the first five outputs from TVM execution
 [[-2.2394986  -0.9680933   3.4041846  -0.14806426 -0.02724874 -1.2441163
  -1.8548993 ]
 [-1.6016592  -1.3846085   0.7641872   2.5430043  -1.7419695  -1.3703678
   0.42491326]
 [-2.0038617  -1.2356598   2.4931228   1.0322791  -1.325198   -1.3400824
  -0.51143134]
 [ 0.16473567 -2.0420618  -0.26682284  0.15265226 -0.6964847   1.1109071
   1.103439  ]
 [-0.8606019  -0.69538236  0.1958623   0.6853092   0.02840531 -0.6652414
   0.22247872]]
Test accuracy of TVM results: 5.30%
</pre></div>
</div>
<div class="sphx-glr-footer class sphx-glr-footer-example docutils container" id="sphx-glr-download-how-to-work-with-relay-build-gcn-py">
<div class="sphx-glr-download docutils container">
<p><a class="reference download internal" download="" href="../../_downloads/dabb6b43ea9ef9d7bd1a3912001deace/build_gcn.py"><code class="xref download docutils literal notranslate"><span class="pre">下载Python源代码:</span> <span class="pre">build_gcn.py</span></code></a></p>
</div>
<div class="sphx-glr-download docutils container">
<p><a class="reference download internal" download="" href="../../_downloads/825671e45a9bdc4733400384984cd9dd/build_gcn.ipynb"><code class="xref download docutils literal notranslate"><span class="pre">下载Jupyter</span> <span class="pre">notebook:</span> <span class="pre">build_gcn.ipynb</span></code></a></p>
</div>
</div>
<p class="sphx-glr-signature"><a class="reference external" href="https://sphinx-gallery.github.io">Gallery generated by Sphinx-Gallery</a></p>
</div>
</div>


           </div>
           
          </div>
          

<footer>

    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
      
        <a href="using_external_lib.html" class="btn btn-neutral float-right" title="在Relay中使用外部库" accesskey="n" rel="next">下一个 <span class="fa fa-arrow-circle-right"></span></a>
      
      
        <a href="index.html" class="btn btn-neutral float-left" title="Work With Relay" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> 上一个</a>
      
    </div>

<div id="button" class="backtop"><img src="../../_static//img/right.svg" alt="backtop"/> </div>
<section class="footerSec">
    <div class="footerHeader">
      <ul class="d-flex align-md-items-center justify-content-between flex-column flex-md-row">
        <li class="copywrite d-flex align-items-center">
          <h5 id="copy-right-info">© 2020 Apache Software Foundation | All right reserved</h5>
        </li>
      </ul>

    </div>

    <ul>
      <li class="footernote">Copyright © 2020 The Apache Software Foundation. Apache TVM, Apache, the Apache feather, and the Apache TVM project logo are either trademarks or registered trademarks of the Apache Software Foundation.</li>
    </ul>

</section>
</footer>
        </div>
      </div>

    </section>

  </div>
  

    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

  </body>
  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script>

  
  
    
    <!-- Theme Analytics -->
    <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-75982049-2', 'auto');
    ga('send', 'pageview');
    </script>

    
   

</body>
</html>